package com.ypf.demo_ssm.config;

import com.alibaba.fastjson.JSON;
import com.ypf.demo_ssm.utils.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应处理类
 */
//Spring框架提供的一个注解，它用于定义全局的异常处理类和全局数据绑定等操作，是一种对控制器进行集中式处理的增强器
@ControllerAdvice(basePackages = {"com.ypf.demo_ssm"})
@Slf4j
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    // 判断是否需要处理响应体
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    // 包装响应体
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 请求的URL
        String url = request.getURI().toString();
        // 请求的来源ip
        String ipAddress = request.getRemoteAddress().getHostString();
        if (request.getHeaders().containsKey("X-forearded-For")) {
            ipAddress = request.getHeaders().getFirst("X-forearded-For");
        }
        log.info("调用信息【URL: {}, IP {}】", url, ipAddress);
        if (body instanceof String) {
            // 特殊处理字符串类型，避免直接包装导致的问题
            return JSON.toJSONString(new ApiResponse<>(HttpStatus.OK.value(), "success", body));
        } else if (body instanceof ApiResponse) {
            return body;
        } else {
            return new ApiResponse<>(HttpStatus.OK.value(), "success", body);
        }
    }


}
